package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 订单处理  支付超时的订单如何处理？每分钟执行一次
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

   // @Scheduled(cron = "0 0/1 * * * ?")
    public void processTimeoutOrder(){
         log.info("订单支付超时{}",new Date());

        //获取当前时间过去的15分钟的时间
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        //调用mapper获取指定条件的所有的支付超时的订单
        List<Orders> ordersList =  orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT,localDateTime);
        //修改这些订单的状态为已取消状态
        if (ordersList !=null && ordersList.size()>0){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时，自动取消");
                orders.setCancelTime(localDateTime.now());
                orderMapper.update(orders);
            });
        }
    }

    /**
     * 派送中的订单未完成,每天凌晨执行一次
     */
   // @Scheduled(cron = "0 0/1 * * * ?")
    public void processDeliveryOrder(){
        log.info("派送中的订单未完成...{}", new Date());
        //获取当前时间过去的1小时的时间
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        //调用mapper获取指定条件的所有的派送中未完成的订单
        List<Orders> orders = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        //修改这些订单的状态为已完成状态
        if (orders !=null && orders.size()>0){
            orders.forEach(orders1 -> {
                orders1.setStatus(Orders.COMPLETED);
                orderMapper.update(orders1);
            });
        }
    }
}
